let canvas = document.getElementById("cvs");
let ctx = canvas.getContext("2d");
let showConfigDetail=false;
let configFixed=false;
const w = innerWidth;
const h = innerHeight;
let settingIcon=document.querySelector('.bi-gear-fill');
let switcher=document.querySelector('.toggle-switch')
let tools=document.querySelector('.tools');
tools.addEventListener('click',(e)=>{
  e.stopPropagation();
})
switcher.onclick=({target})=>{
  let origin=target.className.includes('-on')?'-on':'-off';
  let replaced=origin=='-on'?'-off':'-on';
  configFixed=replaced=='-on'
  target.className=target.className.replace(origin,replaced)
}
document.onclick=()=>{
  if(showConfigDetail&&!configFixed){
    showConfigDetail=false;
    switchConfigVisibility(false);
  }
}
// 背景颜色
let bgColor = "white";
// 线条颜色
let strokeColor = "black";
// 绘制状态
let drawState = false;
// 背景变更状态
let bgChanging=false;
// 每次绘制的起点
let beginPoint = "";
// 当前绘制的坐标数组
let curPoints = [];
// 历史数据 , 收集的数据
let allPoints=[]; 
// 线条宽度
let lineWidth=2;
// 初始化canvas
initCanvas();
function switchConfigVisibility(bool){
  configShow=bool?'show':'hide';
  tIconShow=bool?'hide':'show';
  toolMinWidth=bool?'240px':'unset';
  $('.config')[configShow]();
  $('.t-icon')[tIconShow]()
  $('.tools')[0].style.minWidth=toolMinWidth;
}
settingIcon.addEventListener('click',()=>{
  showConfigDetail=!showConfigDetail;
  switchConfigVisibility(showConfigDetail)
})
/**
 * 根据传入userAgent值判断是否为pc端
 * @param {*} UA userAgent
 * @returns flag 是否为PC端
 */
let platformIsPc = (UA) => {
  let flag = false;
  let phoneArr = ["Mobile", "Android", "iPhone"];
  for (let index = 0; index < phoneArr.length; index++) {
    flag = UA.includes(phoneArr[index]);
    if (flag) {
      break;
    }
  }
  return !flag;
};
/**
 * 初始化事件监听逻辑
 */
let initEvents = () => {
  let { userAgent } = navigator;
  let platformPc = platformIsPc(userAgent);
  if (platformPc) {
    /**
     * canvas画布的mousedown事件回调[绘制预备]
     * @param {Event} e 事件对象
     */
    canvas.onmousedown = canvasDown;
    /**
     * canvas的mousemove事件回调[绘制进行]
     * @param {Event} e 事件对象
     */
    canvas.onmousemove = canvasMove;
    /**
     * 绘制结束重置绘制状态值
     * @param {*} e
     */
    canvas.onmouseup = canvasUp;
  } else {
    // 移动端对应事件处理逻辑
    canvas.ontouchstart = (e) => {
      e.preventDefault();
      e = e.targetTouches[0];
      canvasDown(e);
      // ctx.moveTo(e.pageX, e.pageY);
    };
    canvas.ontouchmove = (e) => {
      if (drawState) {
        e.preventDefault();
        e = e.targetTouches[0];
        canvasMove(e);
        // ctx.lineTo(e.pageX, e.pageY);
        // ctx.stroke();
      }
    };
    canvas.ontouchend = canvasUp
  }
};
initEvents();
function resetChange(){
  setTimeout(() => { bgChanging=false }, 1)
}
/**
 * 绘制开始的回调  屏幕或鼠标单击开始
 * @param {Event} e 事件对象
 */
function canvasDown(e) {

  drawState = true;
  beginPoint = getAxis(e);
}
/**
 * 绘制进行中的回调 
 * @param {Event} e 事件对象 
 */
function canvasMove(e) {
  if(!drawState || bgChanging)return;
  let pObj = getAxis(e);
  curPoints.push(pObj);
  if (curPoints.length > 3) {
    const lastTwoPoints = curPoints.slice(-2);
    const controlPoint = lastTwoPoints[0];
    const endPoint = {
      x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
      y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
    };
    drawLine(beginPoint, controlPoint, endPoint);
    beginPoint = endPoint;
    // collectPoints=
  }
}
/**
 * 绘制结束的回调 [用于重置canvas状态]
 * @param {Event} e 事件对象
 */
function canvasUp(e) {
  e.preventDefault();
  e.stopPropagation();
  drawState = false;
  beginPoint = "";
  if(curPoints.length>3){
    allPoints=allPoints.concat(JSON.parse(JSON.stringify(curPoints))) 
  }
  curPoints = [];
}
/**
 * 设置颜色
 * @param {String} type 设置颜色的类型 eg: bg=>canvas背景颜色 , font=>绘制的字体颜色
 */
function setColor(type) {
  let { value } = document.getElementById(`${type}ColorPicker`);
  if (type == "bg") {
    bgColor = value;
    bgChanging=true;
    $('#modal-1').modal('show');
  } else {
    strokeColor = value;
    // initCanvas();
  }
}
/**
 * 初始化画板
 */
function initCanvas(e) {
  if(e){
    e.stopPropagation();
    e.preventDefault();
  }
  setTimeout(() => {
    bgChanging=false;
  }, 1);
  $('.lang-en').hide();
  canvas.width = w;
  canvas.height = h;
  beginPoint = "";
  curPoints = [];
  allPoints=[];
  drawState=false;
  ctx.fillStyle = bgColor;
  ctx.fillRect(0, 0, w, h);
  ctx.lineWidth = lineWidth;

}

/**
 * 重置背景(不清除内容的前提下重置背景)
 */
function resetBg(){
  canvas.width = w;
  canvas.height = h;
  ctx.fillStyle = bgColor;
  ctx.fillRect(0, 0, w, h);
  ctx.lineWidth = lineWidth;
  let len=allPoints.length;
  beginPoint=allPoints[0];
  // console.log(allPoints,'cur');
  for (let index = 0; index < len; index++) {
      // beginPoint=curPoints[index]
    // let cPoints=curPoints
    // cPoints.push(pObj);
    if (index > 2 && index<len-1) {
      const lastTwoPoints = allPoints.slice(index-1,index+1);
      const controlPoint = lastTwoPoints[0];
      const endPoint = {
        x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
        y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
      };
      drawLine(beginPoint, controlPoint, endPoint);
      beginPoint = endPoint;
      // collectPoints=
    }
  }
  bgChanging=false;
}
/**
 * 下载图片
 */
let canvasToImage = () => {
  const a = document.createElement("a");
  a.href = canvas.toDataURL();
  let d=new Date();
  let yy=d.getFullYear();
  let MM=fillZero(d.getMonth()+1);
  let dd=fillZero(d.getDate());
  let hh=fillZero(d.getHours());
  let mm=fillZero(d.getMinutes());
  let ss=fillZero(d.getSeconds());
  let suffix=`-${yy}${MM}${dd}${hh}${mm}${ss}`;//时间格式  yy-MM-dd hh-mm-ss
  a.download = `canvas${suffix}.png`;
  a.click();
};

/**
 * 补零函数(用于时间数据格式化)
 * @param {*} n 需要格式化的数据
 * @returns 小于10的数据自动补零
 */
function fillZero(n){
  return n>10?n:'0'+n;
}
/**
 * 利用canvas的quadraticCurveTo来绘制圆滑曲线
 * @param {*} beginPoint 开始坐标
 * @param {*} controlPoint 控制坐标
 * @param {*} endPoint 结束坐标
 */
function drawLine(beginPoint, controlPoint, endPoint) {
  ctx.lineWidth=lineWidth;
  ctx.strokeStyle = strokeColor;
  ctx.beginPath();
  ctx.moveTo(beginPoint.x, beginPoint.y);
  ctx.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
  ctx.stroke();
  ctx.closePath();
}
/**
 * 获取坐标
 * @param {Event} e 事件对象
 * @returns {Object} axis=>{x,y}
 */
function getAxis(e) {
  return { x: e.pageX, y: e.pageY };
}

/**
 * 修改线条粗细
 */
function widthChange(){
  let rangeDom=document.querySelector('#lineRange');
  lineWidth=rangeDom.value;

}
/**
 * 切换语言
 * @param {String} type 语言类型 eg:zh,en,jp
 */
function changeLang(type){
  $(`[class*=lang-]`).hide();
  $(`.lang-${type}`).show()
}


